#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基于配置文件的RocketMQ消费者示例
"""

import time
import json
import logging
from rocketmq.client import PushConsumer, ConsumeStatus, ReceivedMessage
from config import ROCKETMQ_CONFIG, MESSAGE_CONFIG, LOGGING_CONFIG

# 配置日志
logging.basicConfig(
    level=getattr(logging, LOGGING_CONFIG["level"]),
    format=LOGGING_CONFIG["format"],
    filename=LOGGING_CONFIG["file"]
)
logger = logging.getLogger(__name__)


def message_callback(msg: ReceivedMessage):
    """
    消息处理回调函数
    
    Args:
        msg: 接收到的消息对象
        
    Returns:
        ConsumeStatus: 消费状态
    """
    try:
        # 解析消息内容
        message_body = msg.body.decode(MESSAGE_CONFIG["encoding"])
        
        # 尝试解析JSON格式的消息
        try:
            message_data = json.loads(message_body)
            logger.info(f"收到JSON消息: {message_data}")
        except json.JSONDecodeError:
            logger.info(f"收到文本消息: {message_body}")
        
        # 记录消息详情
        logger.info(f"消息ID: {msg.id}")
        logger.info(f"消息标签: {msg.tags}")
        logger.info(f"消息键: {msg.keys}")
        logger.info(f"主题: {msg.topic}")
        logger.info(f"队列ID: {msg.queue_id}")
        logger.info(f"消息偏移量: {msg.offset}")
        
        # 处理消息逻辑
        process_message(msg)
        
        return ConsumeStatus.CONSUME_SUCCESS
        
    except Exception as e:
        logger.error(f"处理消息失败: {e}")
        return ConsumeStatus.RECONSUME_LATER


def process_message(msg: ReceivedMessage):
    """
    处理消息的具体业务逻辑
    
    Args:
        msg: 接收到的消息对象
    """
    try:
        # 根据消息标签进行不同的处理
        if msg.tags == "S_C":
            logger.info("处理编译相关消息...")
            # 这里添加您的具体业务逻辑
            # 例如：编译代码、处理编译结果等
            
        elif msg.tags == "ALARM_TAG":
            logger.info("处理告警消息...")
            # 处理告警逻辑
            
        else:
            logger.info(f"处理其他类型消息，标签: {msg.tags}")
            
    except Exception as e:
        logger.error(f"业务处理失败: {e}")


def create_consumer():
    """
    创建并配置消费者
    
    Returns:
        PushConsumer: 配置好的消费者实例
    """
    try:
        # 从配置文件获取参数
        consumer_group = ROCKETMQ_CONFIG["consumer_group"]
        namesrv_addr = ROCKETMQ_CONFIG["namesrv_addr"]
        topic = ROCKETMQ_CONFIG["default_topic"]
        access_key = ROCKETMQ_CONFIG["access_key"]
        secret_key = ROCKETMQ_CONFIG["secret_key"]
        consumer_config = ROCKETMQ_CONFIG["consumer_config"]
        
        logger.info("创建RocketMQ消费者...")
        
        # 创建消费者
        consumer = PushConsumer(consumer_group, orderly=consumer_config["orderly"])
        
        # 设置NameServer地址
        consumer.set_name_server_address(namesrv_addr)
        
        # 设置ACL认证（如果需要）
        if access_key and secret_key:
            consumer.set_session_credentials(access_key, secret_key, "ALIYUN")
            logger.info("已设置ACL认证")
        
        # 订阅主题和消息处理回调
        consumer.subscribe(topic, message_callback, consumer_config["message_tags"])
        logger.info(f"已订阅主题: {topic}, 标签: {consumer_config['message_tags']}")
        
        return consumer
        
    except Exception as e:
        logger.error(f"创建消费者失败: {e}")
        raise


def main():
    """主函数"""
    consumer = None
    
    try:
        logger.info("启动RocketMQ消费者...")
        
        # 创建消费者
        consumer = create_consumer()
        
        # 启动消费者
        consumer.start()
        logger.info("消费者启动成功，开始监听消息...")
        
        # 保持程序运行
        while True:
            time.sleep(1)
            
    except KeyboardInterrupt:
        logger.info("收到中断信号，正在关闭消费者...")
        
    except Exception as e:
        logger.error(f"消费者运行出错: {e}")
        
    finally:
        if consumer:
            consumer.shutdown()
            logger.info("消费者已关闭")


if __name__ == "__main__":
    main() 